/**
 *  转换ant table的sorter对象转换成分页的查询的排序字段
 * @param {object} sorter
 */
export const conventSorter = sorter => {
    const option = {};
    if(sorter)
        if(sorter.order && sorter.field) {
            // 点击排序
            option.sortField = sorter.field;
            if(sorter.order === 'descend') option.isDesc = true;
            else option.isDesc = false;
        } else {
            // 取消排序
            option.sortField = undefined;
            option.isDesc = undefined;
        }
    return option;
};
export const hasPermissions = (data, name) => Array.isArray(data) && data.length > 0 && data.some(item => item === name);

export const categoryTypeCompare = (a, b) => (a.level || 0) - (b.level || 0);

export const availableTypes = (types, typeId) => {
    const index = types.findIndex(item => item.value === typeId);
    if(index === -1)
        return types.slice(0, 1);
    if(index === 0)
        return types.slice(index + 1);
    return types.slice(index);
};

export const sorter = (key, a, b) => {
    if(a[key] > b[key])
        return 1;
    if(a[key] < b[key])
        return -1;
    return 0;
};

/**
 * [getObjById 根据ID获取树上对应id的对象]
 * @param  {[Array]} data [树的数据]
 * @param  {[String]} id   [需要获取的id]
 * @return {[Object]}      [对象]
 */
export const getObjById = (data, id) => {
    if(!data || !data.length || !id) return {};
    const newData = [];
    for(let i = 0; i < data.length; i++) {
        /*eslint-disable  eqeqeq*/
        if(data[i].id == id)
            return data[i];
        if(data[i].items)
            newData.push(...data[i].items);
    }
    return getObjById(newData, id);
};

/**
 * [getPathById 根据ID获取树上对应id的对象]
 * @param  {[Array]} data [树的数据]
 * @param  {[String]} id   [需要获取的id]
 * @return {[Array]}      [path]
 */
export const getPathById = (data, id) => {
    for(let i = 0; i < data.length; i++) {
        const organization = data[i];
        /*eslint-disable  eqeqeq*/
        if(organization.id == id)
            return [i];
        if(organization.items && organization.items.length > 0) {
            const path = getPathById(organization.items, id);
            if(path)
                return [i, 'items'].concat(path);
        }
    }
};


import {formatMessage} from './intl';
export const validateAddCategory = data => {
    const {name, code} = data;
    const msgs = [];
    if(!code)
        msgs.push(
            formatMessage({
                id: 'utils.validateAddCategory.code',
                defaultMessage: '编号'
            })
        );
    if(!name)
        msgs.push(
            formatMessage({
                id: 'utils.validateAddCategory.name',
                defaultMessage: '名称'
            })
        );
    if(msgs.length)
        return `${msgs.join(
            formatMessage({
                id: 'utils.validateAddCategory.comma',
                defaultMessage: '、'
            })
        )}${formatMessage({
            id: 'utils.validateAddCategory.notEmpty',
            defaultMessage: '不能为空'
        })}`;
    return false;
};


export const validateAssist = data => {
    const {id, name, code, productCategoryCode, claimPrice, dealerId, singleQty, maxQty} = data;
    const msgs = [];
    if(!id && !code)
        msgs.push(
            formatMessage({
                id: 'utils.validateAssist.code',
                defaultMessage: '辅料编号'
            })
        );
    if(!name)
        msgs.push(
            formatMessage({
                id: 'utils.validateAssist.name',
                defaultMessage: '辅料名称'
            })
        );
    if(!claimPrice)
        msgs.push(
            formatMessage({
                id: 'utils.validateAssist.claimPrice',
                defaultMessage: '索赔价'
            })
        );
    if(!dealerId)
        msgs.push(
            formatMessage({
                id: 'utils.validateAssist.dealerId',
                defaultMessage: '服务站编号'
            })
        );
    if(!productCategoryCode)
        msgs.push(
            formatMessage({
                id: 'utils.validateAssist.productCategoryCode',
                defaultMessage: '车型编号'
            })
        );
    if(!singleQty)
        msgs.push(
            formatMessage({
                id: 'utils.validateAssist.singleQty',
                defaultMessage: '单车用量'
            })
        );
    if(!maxQty)
        msgs.push(
            formatMessage({
                id: 'utils.validateAssist.maxQty',
                defaultMessage: '最大用量'
            })
        );
    if(msgs.length)
        return `${msgs.join(
            formatMessage({
                id: 'utils.validateAssist.comma',
                defaultMessage: '、'
            })
        )}${formatMessage({
            id: 'utils.validateAssist.notEmpty',
            defaultMessage: '不能为空'
        })}`;
    return false;
};
import {isEqual, groupBy, pickBy} from 'lodash';
export const validateAdd = (data = []) => {
    const {partServiceProperties = [], partServicePrices = [], partDutyUnits = [], tempPartServiceProperties = []} = data;
    const partServicePropertiesList = partServiceProperties.concat(tempPartServiceProperties);
    const errorDetails = [];
    const partServicePricesErrorDetails = [];
    const propertiesObj = {};
    const priceObj = {};
    for(let i = 0; i < partServicePropertiesList.length; i++) {
        const {id, brandId, dealerId, partWarrantyCategoryId, isPreAuthorized, isNeedPicture} = partServicePropertiesList[i];
        if(!brandId || !dealerId || !partWarrantyCategoryId || typeof isPreAuthorized !== 'boolean' || typeof isNeedPicture !== 'boolean')
            return {
                msg: formatMessage({
                    id: 'utils.partServiceProperties.notEmpty',
                    defaultMessage: '品牌服务信息清单中的字段不能为空'
                }),
                errorDetails: []
            };
        if(propertiesObj[brandId])
            errorDetails.push(id);
        else
            propertiesObj[brandId] = 1;
    }
    for(let i = 0; i < partServicePrices.length; i++) {
        const {id, brandId, currency, year, month, price} = partServicePrices[i];
        if(!brandId || !currency || !year || !month || !price)
            return {
                msg: formatMessage({
                    id: 'utils.partServicePrices.notEmpty',
                    defaultMessage: '索赔价清单中的字段不能为空'
                }),
                partServicePricesErrorDetails: []
            };
        const detailOnly = partServicePricesErrorDetails.some(item => isEqual(item, {
            brandId,
            currency,
            year,
            month
        }));
        if(detailOnly)
            return {
                message: `${formatMessage({
                    id: 'utils.partServicePricesErrorDetails.noEqual',
                    defaultMessage: '索赔价清单中，品牌+年月+币种 不能重复'
                })}`,
                partServicePricesErrorDetails
            };
        partServicePricesErrorDetails.push({
            brandId,
            currency,
            year,
            month
        });
    }
    // if(partServicePrices.length)
    //     return {
    //         msg: formatMessage({
    //             id: 'utils.partServicePricesErrorDetails.noEqual',
    //             defaultMessage: '索赔价清单中，品牌+年月+币种 不能重复'
    //         }),
    //         partServicePricesErrorDetails
    //     };
    let flag = 0;
    for(let i = 0; i < partDutyUnits.length; i++) {
        const {isDefault} = partDutyUnits[i];
        if(isDefault)
            flag += 1;
    }
    if(flag > 1)
        return {
            msg: formatMessage({
                id: 'utils.validateAdd.isDefault',
                defaultMessage: '清单中是否首选项只能有一个'
            }),
            errorDetails: []
        };
    return false;
};
export const renderBoolean = value => {
    if(typeof value !== 'boolean') return value;
    else if(value)
        return formatMessage({
            id: 'utils.yes',
            defaultMessage: '是'
        });
    return formatMessage({
        id: 'utils.no',
        defaultMessage: '否'
    });
};

export const validateEqual = (record, data = []) => data.some(item => {
    const {id, brandId} = record;
    return brandId && id !== item.id && brandId === item.brandId;
});

/* eslint-disable prefer-const, no-bitwise, no-mixed-operators */
export const uuid = () => 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
    let r = Math.random() * 16 | 0,
        v = c === 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
});
